package com.tuanchau.android.englishtooltip.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

import com.tuanchau.android.englishtooltip.Global;
import com.tuanchau.android.englishtooltip.R;
import com.tuanchau.android.englishtooltip.database.DatabaseManager;
import com.tuanchau.android.englishtooltip.database.WordStruct;

public class ListWordActivity extends Activity implements OnItemClickListener {

	private final int REQUEST_TO_EDITWORD = 10;

	private ListView listView;
	private ListWordAdapter adapter;
	private DatabaseManager db;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_word);
		initView();
	}

	private void initView() {
		listView = (ListView) findViewById(R.id.activity_list_word);
		registerForContextMenu(listView);

		db = new DatabaseManager(getApplicationContext());

		adapter = new ListWordAdapter(this, db.getAll());

		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		listView.setSelection(adapter.getCount() - 1);

		if (adapter.getCount() <= 0) {
			onAddItemClicked();
			Toast.makeText(this, "Add your first new word :)",
					Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = getIntent();
			String action = intent.getAction();
			if (action.equals(Global.ACTION_OPEN_WORD_DETAIL)) {
				int index = getSharedPreferences(Global.PREF_FILE_NAME,
						MODE_PRIVATE).getInt(Global.PREF_KEY_CURRENT_INDEX, -1);
				if (index != -1) {
					int pos = adapter.findIndexPosition(index);
					if (pos >= 0) {
						openWordDetail(pos, Global.REQUEST_TO_WORD_DETAIL_ON_WIDGET);
					}
				}
			}
			else if(action.equals(Global.ACTION_ADD_WORD)) {
				onAddItemClicked();
			}
		}

	}

	// ---------------- create menu -------------------//
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_word_menu, menu);
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.list_word_context_menu, menu);
		menu.setHeaderTitle(R.string.context_menu_header);

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add:
			onAddItemClicked();
			return true;
		case R.id.menu_setting:
			onSettingItemClicked();
			return true;
			// case R.id.menu_close:
			// onCloseItemClicked();
			// return true;
		default:
			return false;
		}
	}

	private void onAddItemClicked() {
		Intent intent = new Intent(this, EditWordActivity.class);
		intent.putExtra(Global.STATE_CODE, Global.STATE_NEWWORD);
		if (adapter.getCount() <= 0)
			intent.putExtra(Global.KEY_FIRSTWORD, true);
		else {
			intent.putExtra(Global.KEY_FIRSTWORD, false);
		}
		startActivityForResult(intent, REQUEST_TO_EDITWORD);

	}

	private void onSettingItemClicked() {
		Intent intent = new Intent(getApplicationContext(),
				SettingActivity.class);
		startActivity(intent);
	}

	// private void onCloseItemClicked() {
	// finish();
	// }

	@Override
	public boolean onContextItemSelected(MenuItem aItem) {
		onDeleteItemClicked(aItem);
		return true;
	}

	private void onDeleteItemClicked(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();

		int position = menuInfo.position;
		WordStruct w = adapter.get(position);
		db.delete(w.id);
		adapter.remove(position);
		adapter.notifyDataSetChanged();
		Toast.makeText(this, w.word + " was deleted", Toast.LENGTH_SHORT)
				.show();
		
		if(adapter.getCount() <= 0) {
			onAddItemClicked();
		}
	}

	// ---------------- On receive data from another activity ----------------//
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
		case REQUEST_TO_EDITWORD:
			if (resultCode == Activity.RESULT_OK) {
				onFromEdit(data);
			}
			else if (adapter.getCount() <= 0) {
				finish();
			}
			break;
		case Global.REQUEST_TO_WORD_DETAIL_ON_LIST:
			if (resultCode == Activity.RESULT_OK) {
				onFromDetail(data);
			}
			break;
		
		case Global.REQUEST_TO_WORD_DETAIL_ON_WIDGET:
			boolean doExit = data.getBooleanExtra(Global.KEY_DO_EXIT, false);
			if(doExit) {
				finish();
			}
			break;
		default:
			break;
		}
	}

	private void onFromDetail(Intent data) {

		int state = data.getIntExtra(Global.STATE_CODE, Global.STATE_NOCHANGE);
		if (state == Global.STATE_EDIT) {
			int position = data.getIntExtra(Global.KEY_WORD_POSITION, 0);
			final WordStruct w = adapter.get(position);
			w.word = data.getStringExtra(Global.KEY_WORD);
			w.type = data.getStringExtra(Global.KEY_TYPE);
			w.pron = data.getStringExtra(Global.KEY_PRONUNCIATION);
			w.mean = data.getStringExtra(Global.KEY_MEAN);

			byte[] newImage = data.getByteArrayExtra(Global.KEY_IMAGE);

			if (newImage == null) {
				w.image = null;
				w.bitmap = null;
			} else if (!newImage.equals(w.image)) {
				w.image = newImage;
				w.bitmap = BitmapFactory.decodeByteArray(newImage, 0,
						newImage.length);

			}

			adapter.notifyDataSetChanged();
			db.update(w);
			getSharedPreferences(Global.PREF_FILE_NAME, MODE_PRIVATE).edit()
					.putBoolean(Global.PREF_KEY_UPDATE_WORD, true).commit();
		}
	}

	private void onFromEdit(Intent data) {
		int state = data.getIntExtra(Global.STATE_CODE, Global.STATE_EDIT);
		if (state == Global.STATE_NEWWORD) {
			int id = adapter.getLastId() + 1;
			String word = data.getStringExtra(Global.KEY_WORD);
			String pron = data.getStringExtra(Global.KEY_PRONUNCIATION);
			String type = data.getStringExtra(Global.KEY_TYPE);
			String mean = data.getStringExtra(Global.KEY_MEAN);
			byte[] image = data.getByteArrayExtra(Global.KEY_IMAGE);

			WordStruct w = new WordStruct(id, word, type, pron, mean, image);

			if (image != null) {
				w.bitmap = BitmapFactory
						.decodeByteArray(image, 0, image.length);
			}

			adapter.add(w);
			adapter.notifyDataSetChanged();
			db.insert(w);
			listView.setSelection(adapter.getCount() - 1);
			getSharedPreferences(Global.PREF_FILE_NAME, MODE_PRIVATE).edit()
					.putBoolean(Global.PREF_KEY_UPDATE_WORD, true).commit();
		} else if (state == Global.STATE_NOCHANGE) {
			if (adapter.getCount() <= 0) {
				finish();
			}
		}

	}

	// ---------------- On click on list word item ----------------//
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		openWordDetail(position, Global.REQUEST_TO_WORD_DETAIL_ON_LIST);
	}

	private void openWordDetail(int position, int request) {
		WordStruct w = adapter.get(position);

		Intent intent = new Intent(ListWordActivity.this,
				WordDetailActivity.class);
		intent.putExtras(new Bundle());
		intent.putExtra(Global.KEY_WORD_POSITION, position);
		intent.putExtra(Global.KEY_WORD, w.word);
		intent.putExtra(Global.KEY_TYPE, w.type);
		intent.putExtra(Global.KEY_PRONUNCIATION, w.pron);
		intent.putExtra(Global.KEY_MEAN, w.mean);
		intent.putExtra(Global.KEY_IMAGE, w.image);

		startActivityForResult(intent, request);
	}

}
